/*
 * Copyright 2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */



import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;

import org.example.user.User;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
import org.springframework.http.converter.xml.SourceHttpMessageConverter;
import org.springframework.oxm.XmlMappingException;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.web.client.RestTemplate;

public class UserClient {

    public static void main(String[] args) throws XmlMappingException, IOException {
    	for (int i=1; i<1000; i++) {
   			postForLocation(String.valueOf(i));
    	}
    }

	private static void postForLocation(String id) throws IOException {
		RestTemplate restTemplate = new RestTemplate();
    	List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>();
    	list.add(new SourceHttpMessageConverter<Source>());
    	restTemplate.setMessageConverters(list);
    	String content = readFileAsString("src/main/resources/user-instance.xml").replaceAll("ID", id);
    	URI resultUrl = 
    		restTemplate.postForLocation("http://localhost:8888/post/", 
    			new StreamSource(new StringReader(content)));
    	getObject(resultUrl);
	}
	
	private static void getObject(URI resultUrl) {
		RestTemplate restTemplate = new RestTemplate();
    	List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>();
    	Jaxb2Marshaller jaxb2 = new Jaxb2Marshaller();
    	jaxb2.setContextPath("org.example.user");
    	list.add(new MarshallingHttpMessageConverter(jaxb2));
    	restTemplate.setMessageConverters(list);
		User user = restTemplate.getForObject(resultUrl, User.class);
		System.out.println(user.getId());
	}

	private static String readFileAsString(String filePath) throws java.io.IOException{
	    byte[] buffer = new byte[(int) new File(filePath).length()];
	    BufferedInputStream f = new BufferedInputStream(new FileInputStream(filePath));
	    f.read(buffer);
	    return new String(buffer);
	}	

}
